package com.example.springssm.controller;

import com.example.springssm.bean.Employee;
import com.example.springssm.common.PageResult;
import com.example.springssm.common.R;
import com.example.springssm.service.EmployeeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/employees") // RESTful 风格，资源用复数名词
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    // 根据ID查询员工 - GET /api/employees/{id}
    @GetMapping("/{id}")
    public R getEmployeeById(@PathVariable Long id) {
        return R.success(employeeService.getEmployeeById(id));
    }

    // 查询所有员工 (列表) - GET /api/employees
    @GetMapping
    public R<List<Employee>> getAllEmployees() {
        return R.success(employeeService.getAllEmployees());
    }

    // 分页查询员工 - GET /api/employees/page?pageNum=1&pageSize=10
    @GetMapping("/page")
    public PageResult<Employee> getEmployeesByPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return employeeService.getEmployeesByPage(pageNum, pageSize);
    }

    // 新增员工 - POST /api/employees
    @PostMapping
    public R addEmployee(@RequestBody @Valid Employee employee) { // @Valid 触发校验
        employeeService.addEmployee(employee);
        return R.success();
    }

    // 更新员工信息 - PUT /api/employees/{id}
    @PutMapping("/{id}")
    public R updateEmployee(@PathVariable Long id, @RequestBody @Valid Employee employee) {
        employee.setId(id); // 确保更新的是指定ID的员工
        employeeService.updateEmployee(employee);
        return R.success();
    }

    // 删除员工 - DELETE /api/employees/{id}
    @DeleteMapping("/{id}")
    public R deleteEmployee(@PathVariable Long id) {
        employeeService.deleteEmployee(id);
        return R.success();
    }
}
